package com.lxl.springsecurity1.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class SecurityController {
    @GetMapping("/index") //首页的访问路径
    public String index(){
        return "welcome";
    }

    @GetMapping("/level{num}/{id}") //示例：访问menu1/1将返回menu1/1.html
    public String menu(@PathVariable("num")int num, @PathVariable("id")int id){
        return "pages/level"+num+"/"+id;
    }

    @GetMapping("/toLogin") //自定义登录页的访问路径
    public String toLogin(HttpServletRequest request){
        String msg= (String) request.getSession().getAttribute("msg");
        if(msg!=null){
            request.setAttribute("msg",msg);
        }
        return "pages/login";
    }



    @GetMapping("/toLogin/error") //登录失败发生异常时的访问路径
    public String tologin(HttpServletRequest request, Model model){
        AuthenticationException authenticationException = (AuthenticationException) request.getSession()
                .getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        if (authenticationException instanceof UsernameNotFoundException || authenticationException instanceof BadCredentialsException) {
            model.addAttribute("msg","用户名或密码错误");
        } else if (authenticationException instanceof DisabledException) {
            model.addAttribute("msg","用户已被禁用");
        } else if (authenticationException instanceof LockedException) {
            model.addAttribute("msg","账户被锁定");
        } else if (authenticationException instanceof AccountExpiredException) {
            model.addAttribute("msg","账户过期");
        } else if (authenticationException instanceof CredentialsExpiredException) {
            model.addAttribute("msg","证书过期");
        }
        return "pages/login";
    }
}
